﻿var myhost = "https://localhost:5011"; // dev接口host

// 报告服务api host
var fileApi = '/file';
var reportApi = '/report';
var SmartForcastApi = '/forcast';
var fieidApi = '/FieldManager';
// AI体检页面定时器变量
var timer,
    timer2,
    timer3,
    timer4,
    timer5,
    timer6;
if (timer || timer2 || timer3 || timer4 || timer5 || timer6) {
    debugger;
    clearInterval(timer);
    clearInterval(timer2);
    clearInterval(timer3);
    clearInterval(timer4);
    clearInterval(timer5);
    clearInterval(timer6);
    console.log("清理定时器完毕！");
}



function getHeader() {
    var token = "";
    if (localStorage.BaseCode == undefined) {
        token = ""
    } else {
        token = JSON.parse(localStorage.BaseCode).Authorization;
    }
    return "Bearer " + token;
}

function setHeader(XMLHttpRequest) {
    var token = "";
    if (localStorage.BaseCode == undefined) {
        token = ""
    } else {
        token = JSON.parse(localStorage.BaseCode).Authorization;
    }
    debugger
    XMLHttpRequest.setRequestHeader("Authorization", "Bearer " + token);
}

function setTableHeader() {
    var headers = {};
    var token = "";
    if (localStorage.BaseCode == undefined) {
        token = ""
    } else {
        token = JSON.parse(localStorage.BaseCode).Authorization;
    }
    headers["Authorization"] = "Bearer " + token;

    return headers;
}

function number(number, decimals, dec_point, thousands_sep) {
    /*
     * 参数说明：
     * number：要格式化的数字
     * decimals：保留几位小数
     * dec_point：小数点符号
     * thousands_sep：千分位符号
     * */
    number = (number + '').replace(/[^0-9+-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.ceil(n * k) / k;
        };
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    var re = /(-?\d+)(\d{3})/;
    while (re.test(s[0])) {
        s[0] = s[0].replace(re, "$1" + sep + "$2");
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}
//封装ajax请求

//通用异步方法
this.ajaxOption = function (url, type) {
    return {
        url: url,
        type: type == undefined ? "post" : type,
        dataType: "json",
        timeout: 60000,
        beforeSend: function (XMLHttpRequest) {
            //showLoading();
            setHeader(XMLHttpRequest)
        },
        complete: function () {
            //hideLoading();
        },
        success: function (xhrResult) {
            if (isLoading)
                layer.close(index)
            this.callback(xhrResult);
            //debugger
            //if (xhrResult.code === 0) {
            //    this.callback(xhrResult);
            //} else {
            //    //返回异常提示信息
            //    layer.msg(xhrResult.msg);
            //}
        },
        error: function (xhr, errorType, error) {
            if (isLoading)
                layer.close(index)
            debugger
            if (xhr.status == 401) {
                if (window.top != window.self) {
                    return top.location.href = xhr.responseJSON.msg // '/';//location.hash 
                }
                return window.location.href = xhr.responseJSON.msg
            } else if (xhr.status >= 403 && xhr.status < 500) {
                //提示权限问题
                layer.msg(xhr.responseJSON.msg);
            } else if (xhr.status === 0) {
                return window.location.href = "/"
            } else {
                //系统错误
                layer.msg("系统忙，稍后重试");
            }
            //messager('Ajax request error : ' + error, 'error');
        }
    }
}
var index;
var isLoading = false;
this.ajax = function (url, type, dataType, data, callback, contentType, isLoad, processData) {
    debugger;
    if (isLoad == null || isLoad == "") {
        isLoad = false;
    }
    if (processData == null || processData == "") {
        processData = true
    }
    isLoading = isLoad;
    if (isLoad) {
        index = layer.load(1, {
            shadeClose: false,
            title: '加载中..'
        });
    }
    contentType = contentType || false;
    var option = this.ajaxOption(url, type);
    option.dataType = dataType;
    option.data = data;
    option.callback = callback;
    option.contentType = contentType;
    option.processData = processData;
    console.log(option);
    $.ajax(option);
}


Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function FormatNumber(data, fixedLen) {
    if ((data == null) || (data == undefined) || (data == '')) {
        return "0"
    }
    console.log(typeof (data));
    if (typeof (data) == "string") {
        data = parseInt(data);
    }
    return data.toFixed(fixedLen).replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
}

function getRequest() {
    debugger;
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = "";
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            if (strs[i].split("=")[0] == "proId") {
                theRequest = unescape(strs[i].split("=")[1]);
            }
        }
    }
    return theRequest.replace("\'", "").replace("\'", "");
}

function pageName() {

    if (location.href.indexOf('#') > -1) {
        var arr = location.href.split('#')[1].split('/')
        return arr[arr.length - 1];
    } else {
        return location.pathname.split('.')[0];
    }
}
///selectIds 需要绑定数据源的下拉框id 数组，url 请求的地址，form rendenr的form
function QueryItemNameCodeLst(selectIds, url, value, form) {
    debugger
    ajax(url, "get", "Json", {}, function (res) {
        for (var i = 0; i < selectIds.length; i++) {
            var selectId = selectIds[i]
            if (selectId.indexOf("#") != 0) {
                selectId = '#' + selectId
            }

            $(selectId).empty();
            $(selectId).append("<option value=''>请选择</option>")

            if (res.code == "0") {
                for (var k = 0; k < res.data.length; k++) {
                    $(selectId).append("<option value='" + res.data[k].ItemCode + "'>" + res.data[k].ItemName + "</option>");
                }

            }
        }
        form.render();
        return res.data;
    }, "application/json", true);

}

function GetInterfaceButton() {
    $.ajax({
        url: '/Admin/GetInterfacePermission',
        type: 'POST',
        beforeSend: function (XMLHttpRequest) {
            setHeader(XMLHttpRequest);
        },
        dataType: 'json',
        data: {
            Interface: pageName()
        },
        success: function (res) {

            // 成功处理逻辑
            if (res.code == 0) {
                debugger
                data = res.data;

                for (var i = 0; i < data.length; i++) {
                    if (data[i].description == "1") {
                        if (data[i].isshow == "是") {
                            $('#' + data[i].ButtonID).css('display', '');
                        } else {
                            $('#' + data[i].ButtonID).css('display', 'none');
                        }
                    }
                    else if (data[i].description == "2") {
                        if (data[i].isshow == "是") {
                            $('*[lay-event="' + data[i].ButtonID + '"]').css('display', '');
                        } else {
                            $('*[lay-event="' + data[i].ButtonID + '"]').css('display', 'none');
                        }
                    }

                }

            } else {
                layer.msg(res.msg);
            }
        },
        error: function (res) {
            // 错误时处理逻辑
        }
    });
}

jQuery.prototype.serializeObject = function () {

    var obj = new Object();

    $.each(this.serializeArray(), function (index, param) {
        if (!(param.name in obj)) {

            obj[param.name] = param.value;
        }
    });

    return obj;
};

function GetCurrentDate() {
    var now = new Date();
    var year = now.getFullYear(); //得到年份
    var month = now.getMonth() + 1;//得到月份
    var date = now.getDate();//得到日期

    return year + "." + month + "." + date

}

function GetCurrentWeek() {
    var now = new Date();
    var day = now.getDay();//得到周几
    var week;
    var arr_week = new Array("周日", "周一", "周二", "周三", "周四", "周五", "周六");
    week = arr_week[day];

    return week;
}


function UploadImg(upload, id, url, data, before, callback) {
    var headers = setTableHeader();
    //headers['Content-Type'] = 'application/json; charset=utf-8';
    //执行实例
    //var upIndex = layer.load(1, {
    //    shadeClose: false,
    //    title: '加载中..'
    //});
    var uploadInst = upload.render({
        elem: id //绑定元素
        , url: url //上传接口
        , data: data
        , headers: headers
        , acceptMime: 'image/jpg, image/png'
        , before: function (obj) {
            before(obj);
        }
        , done: function (res) {
            //layer.close(upIndex)
            //上传完毕回调
            callback(res);
        }
        , error: function (xhr, errorType, error) {
            // layer.close(upIndex)
            //请求异常回调
            if (xhr.status == 401) {
                if (window.top != window.self) {
                    return top.location.href = xhr.responseJSON.msg // '/';//location.hash 
                }
                return window.location.href = xhr.responseJSON.msg
            } else if (xhr.status >= 403 && xhr.status < 500) {
                //提示权限问题
                layer.msg(xhr.responseJSON.msg);
            } else if (xhr.status === 0) {
                return window.location.href = "/"
            } else {
                //系统错误
                layer.msg("系统忙，稍后重试");
            }
        }
    });
}
var upIndex
function UploadFile(upload, id, url, data, acceptMime, before, callback) {
    debugger
    var headers = setTableHeader();
    //upIndex =layer.load(1, {
    //   shadeClose: false,
    //   title: '加载中..'
    //});
    debugger
    //执行实例
    var uploadInst = upload.render({
        elem: id //绑定元素
        , url: url //上传接口
        , data: data
        , headers: headers
        , accept: "file"
        , acceptMime: acceptMime
        , before: function (obj) {
            before(obj, this.item);
        }
        , done: function (res) {
            // layer.close(upIndex)
            //上传完毕回调
            callback(res);
        }
        , error: function (xhr, errorType, error) {
            // layer.close(upIndex)
            //请求异常回调
            if (xhr.status == 401) {
                if (window.top != window.self) {
                    return top.location.href = xhr.responseJSON.msg // '/';//location.hash 
                }
                return window.location.href = xhr.responseJSON.msg
            } else if (xhr.status >= 403 && xhr.status < 500) {
                //提示权限问题
                layer.msg(xhr.responseJSON.msg);
            } else if (xhr.status === 0) {
                return window.location.href = "/"
            } else {
                //系统错误
                layer.msg("系统忙，稍后重试");
            }
        }
    });
}

// 格式化金额和数字千分位加逗号
function formatNumber(num) {

    return (num + '').replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,');

}